package com.hissy.common.design.create.singleton;

/**
 * Created by zhangyanfei on 2019/4/4.
 * 线程安全问题
 *
 * @author zhangyanfei
 * @date 2019/04/04
 */
public class Singleton {

    private Singleton() {}

    private static Singleton singleton = null;

    public static Singleton getInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }

    /**
     * Thread safe
     */
    public static synchronized Singleton getSafeInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }

    /**
     * 双重检测 可能存在bug     jvm优化执行顺序 可以返回null
     *
     * singleton = new Singleton();
     *
     * 分配内存
     * 将对象放进内存
     *
     * @return
     */
    public static Singleton getSingletonSafe() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }

    private static class LazyHolder {
        private static final Singleton singleton = new Singleton();
    }

    /**
     * 静态内部类
     * 相比加锁最好
     *
     * @return
     */
    public static Singleton getSingleton() {
        return LazyHolder.singleton;
    }

}
